//
//  TopicViewController.swift
//  ReadHub
//
//  Created by 龙轶群 on 2017/5/11.
//  Copyright © 2017年 longyiqun. All rights reserved.
//

import Foundation
import UIKit
import Alamofire
import SwiftyJSON
import DGElasticPullToRefresh
import FDTemplateLayoutCell
import AlamofireImage
import SwiftMoment
import PKHUD
import SwiftyUserDefaults
import AvatarImageView
import SKPhotoBrowser
import Presentr
import AlertOnboarding
import SCLAlertView
import FSPagerView
import SwiftWebVC
import Reachability
import SwiftyDrop



// 热门话题 Controller
class TopicViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UMSocialShareMenuViewDelegate, AlertOnboardingDelegate {
    
    func alertOnboardingSkipped(_ currentStep: Int, maxStep: Int) {
        print("Onboarding skipped the \(currentStep) step and the max step he saw was the number \(maxStep)")
    }
    
    func alertOnboardingCompleted() {
        print("Onboarding completed!")
    }
    
    func alertOnboardingNext(_ nextStep: Int) {
        print("Next step triggered! \(nextStep)")
    }
    
    
    /* *********全局变量开始********** */
    
    var alertView: AlertOnboarding!
	
	let interactor = Interactor()
	
    // 主表格
    var mainTableView = UITableView()
	
	var pagerViewControl = FSPageControl()
	
	var ADHomePages = ["https://readhub.me","https://longyiqun.com/ReadHub/ad.html","https://longyiqun.com/ReadHub/ads.html"]
	
    
    // 主表格的下拉View
    let pullLoadingView = DGElasticPullToRefreshLoadingViewCircle()
    
    // 所有热门话题集合
    var topics: NSMutableArray = []
    var zanArray: [Int] = [Int]()
	var jubaoArray: [Int] = [Int]()
    var topicImages = [Int: String]()
    // 当前页最后一个话题OrderID
    var lastOrder: Int = 0
    
    // 当前页最开始一个话题OrderID
    var firstOrder: Int = 0
    
    //表格底部用来提示数据加载的视图
    var loadMoreView: UIView?
    
    //用了记录当前是否允许加载新数据（正则加载的时候会将其设为false，放置重复加载）
    var loadMoreEnable = true
    
    // 图片Cache
    var cache:NSCache<AnyObject, AnyObject>!
    var task: URLSessionDownloadTask!
    var session: URLSession!
    
    @IBOutlet weak var sponsorsButton: UIButton!
    
    // 头像
    var avatarImageView: AvatarImageView!
    
    let primaryColor = #colorLiteral(red: 0.6271930337, green: 0.3653797209, blue: 0.8019730449, alpha: 1)
    
    let primaryColorDark = #colorLiteral(red: 0.5373370051, green: 0.2116269171, blue: 0.7118118405, alpha: 1)
	
	fileprivate let imageNames = ["1jpg","2jpg","3jpg"]
	
    
    
    
    /* *********全局变量结束********** */
    
    // 点击赞助商
    @IBAction func tappedSponsorsButton(_ sender: UIButton) {
		
		let presenter: Presentr = {
			let customPresenter = Presentr(presentationType: .topHalf)
			customPresenter.transitionType = nil
			customPresenter.dismissTransitionType = nil
			customPresenter.dismissAnimated = true

			return customPresenter
		}()
		
		let controller = SponsorsViewController()
		
		customPresentViewController(presenter, viewController: controller, animated: true, completion: nil)

    }
    
    // 每次页面渲染, 检查头像 & 第一次进入引导页面
    override func viewDidAppear(_ animated: Bool) {
        
        super.viewDidAppear(animated)
        
        // 获取是否第一次打开APP
        let isFirst = UserDefaults.standard.string(forKey: "isFirst")
        
        // 如果是第一次, 则弹出引导页
        if isFirst == "1" {
            
        } else {
            //First, declare datas
            let arrayOfImage = ["image1", "image2", "image3"]
            let arrayOfTitle = ["创建账号", "开启站内信和通知", "出发"]
            let arrayOfDescription = ["创建并登陆你的账号, 可以同步你的收藏, 开启全新评论!",
                                      "在个人设置页面, 打开站内信和通知选项, 可以收到我们的精彩推荐!",
                                      "来吧, 让我们看看这个世界都发生了什么!"]
            
            //Simply call AlertOnboarding...
            self.alertView = AlertOnboarding(arrayOfImage: arrayOfImage, arrayOfTitle: arrayOfTitle, arrayOfDescription: arrayOfDescription)
            self.alertView.titleSkipButton = "跳过"
            self.alertView.titleGotItButton = "完成"
            
            self.alertView.delegate = self
            
            
            //... and show it !
            self.alertView.show()
            
            // 更新本地信息
            UserDefaults.standard.set("1", forKey: "isFirst")
        }
        
        UIApplication.shared.statusBarStyle = .lightContent
        
        // 先移去现有的, 再去获取
        avatarImageView.removeFromSuperview()
        getUserInfo()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    // 一次性解决status bar颜色问题
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    
    /* *********流程开始********* */
    
    override func viewDidLoad() {
        
        // override
        super.viewDidLoad()
		
        // 设置友盟分享Delegate到自己的view上
        UMSocialUIManager.setShareMenuViewDelegate(self)
        
        // 初始化图片Cache
        session = URLSession.shared
        task = URLSessionDownloadTask()
        self.cache = NSCache()
        
        // 设置Edge,要不然tableview最后一个cell会被TabBar覆盖住
        self.edgesForExtendedLayout = UIRectEdge()
        self.automaticallyAdjustsScrollViewInsets = false;
        
        // 用户信息
        getUserInfo()
        
        // 获取最新热门话题
        getTopics(isMore: false)
		
		// 检查网络情况
		getWiFiOrNetWork()
    }
	
	func getWiFiOrNetWork() -> () {
		
		let reachability = Reachability()!
		
		reachability.whenReachable = { reachability in
			if reachability.connection == .wifi {
				print("Reachable via WiFi")
				Drop.down("正在使用WIFI中, 可以放心浏览", state: .success)
			} else {
				print("Reachable via Cellular")
				Drop.down("正在使用移动网络中, 小心流量哦", state: .warning)
			}
		}
		reachability.whenUnreachable = { _ in
			print("Not reachable")
		}
		
		do {
			try reachability.startNotifier()
		} catch {
			print("Unable to start notifier")
		}
	}
    
    // 获取用户信息
    internal func getUserInfo() -> () {
        
        // 头像View
        avatarImageView = AvatarImageView(frame: CGRect(x: 17, y: 34, width: 32, height: 32))
        
        // 添加头像view的config
        struct Config: AvatarImageViewConfiguration { var shape: Shape = .circle }
        avatarImageView.configuration = Config()
        
        // 获取用户头像数据
        avatarImageView.dataSource = UserData()
        
        // 添加view到主页面
        view.addSubview(avatarImageView)
		
		avatarImageView.isUserInteractionEnabled = true
		
		let avatarImageViewTapped: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(TopicViewController.TappedAvatarImageView(sender:)))
		
		avatarImageViewTapped.numberOfTapsRequired = 1
		avatarImageView.addGestureRecognizer(avatarImageViewTapped)
		
    }

	@objc func TappedAvatarImageView(sender: UITapGestureRecognizer) -> () {
		self.tabBarController?.selectedIndex = 2
	}

    // 获取数据主流程
    internal func getTopics(isMore: Bool) -> () {
        
        var parameters: Parameters = [:]
        
        // 根据是不是获取更多来定义Parameters
        if (!isMore) {
            topics = []
            
            parameters = ["pageSize": "20"]
        } else {
            loadMoreEnable = false
            parameters = ["lastCursor": self.firstOrder, "pageSize": "10"]
        }
        
        // 解析Topic最新的
        Alamofire.request(Constants.topicURL, parameters: parameters).responseJSON { response in
            
            if let JSONEntity = response.result.value {
                
                let jsonData = JSON(JSONEntity)
                
                // 判断节点数量大于0
                if (jsonData["data"].count > 0){
                    
                    // 获得当前最大的Order以及最小的Order
                    self.lastOrder = jsonData["data"][0]["order"].int!
                    self.firstOrder = jsonData["data"][jsonData["data"].count - 1]["order"].int!
                    
                    // 循环取Topic填充数组
                    for (_, topicDataArray): (String, JSON) in jsonData["data"] {
                    
                        // 临时Topic对象
                        let topic = Topic()
                        
                        // Topic基本信息
                        topic.id = topicDataArray["id"].string
                        topic.title = topicDataArray["title"].string
                        topic.createdAt = topicDataArray["createdAt"].string
                        topic.publishDate = topicDataArray["publishDate"].string
                        topic.updatedAt = topicDataArray["updatedAt"].string
                        topic.summary = topicDataArray["summary"].string
                        topic.order = topicDataArray["order"].int
                        
                        // 暂时不用
                        topic.relatedTopicArray = nil
                        
                        // Topic的relate topic
                        if(topicDataArray["newsArray"].count > 0) {
                        
                            for(_, newsSubJSON): (String, JSON) in topicDataArray["newsArray"] {
                                
                                // 临时NewsArray对象
                                let news: NewsArrayUnit = NewsArrayUnit()
                                news.authorName = newsSubJSON["authorName"].string
                                news.duplicatedId = newsSubJSON["duplicatedId"].int
                                news.groupId = newsSubJSON["groupId"].int
                                news.id = newsSubJSON["id"].int
                                news.mobileUrl = newsSubJSON["mobileUrl"].string
                                news.publishDate = newsSubJSON["publishDate"].string
                                news.siteName = newsSubJSON["siteName"].string
                                news.title = newsSubJSON["title"].string
                                news.url = newsSubJSON["url"].string
                                
                                // 添加news到数组中
                                topic.newsArray?.append(news)
                            }
                        }  
                  
                        // 添加topic到数组中
                        self.topics.add(topic)
                    }
                }
            }
            
            // 如果是获取更多，则重新加载TableView，否则开始渲染UI视图
            if (!isMore) {
                self.setupUI()
            } else {
                self.mainTableView.reloadData()
                self.loadMoreEnable = true
            }
        }
    }
    
    
    // 渲染UI开始
    internal func setupUI() -> () {
    
        // 设置主TableView
        let mainTableRect: CGRect = CGRect(x: 0, y: Constants.statusBarHeight, width: self.view.bounds.width, height: self.view.bounds.height - Constants.statusBarHeight)
        self.mainTableView = UITableView(frame: mainTableRect, style: UITableViewStyle.plain)
        self.mainTableView.dataSource = self
        self.mainTableView.delegate = self
        self.mainTableView.register(UINib(nibName: "TopicTableViewCell", bundle: nil), forCellReuseIdentifier: "TopicTableViewCell")
        
        // separator样式
        self.mainTableView.separatorStyle = .none
        
        // 不显示侧边滑动条
        self.mainTableView.showsVerticalScrollIndicator = false
        
        // 预估高度 （动态高度的时候一定要设置）
        self.mainTableView.estimatedRowHeight = 100
        self.mainTableView.rowHeight = UITableViewAutomaticDimension
        
        // 设置主TableView的下拉view
        pullLoadingView.tintColor = Constants.mainTextColor
        self.mainTableView.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in
            
            self?.refreshMainTableView()
            
            self?.mainTableView.dg_stopLoading()
            }, loadingView: pullLoadingView)

        self.mainTableView.dg_setPullToRefreshFillColor(Constants.mainBackGroundColor)
        self.mainTableView.dg_setPullToRefreshBackgroundColor(self.mainTableView.backgroundColor!)
        
        // 上拉刷新
        self.setupInfiniteScrollingView()
        self.mainTableView.tableFooterView = self.loadMoreView
		
		// TableView 头部 - banner轮播图
		let pagerViewWith = self.mainTableView.frame.size.width
		let pagerViewFrame = CGRect(x: 0, y: 0, width: Int(pagerViewWith), height: Int(pagerViewWith) / 2)
		let pagerView = FSPagerView(frame: pagerViewFrame)
		pagerView.dataSource = self
		pagerView.delegate = self
		pagerView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "cell")
		pagerView.isInfinite = true
		pagerView.automaticSlidingInterval = 3.0
		//pagerView.transformer = FSPagerViewTransformer(type: .zoomOut)
		
		// TableView 头部 - banner轮播图 - page Control
		let pageControlWidth = Int(pagerViewWith) / 3
		let pagerControlFrame = CGRect(x: Int(pagerViewWith) * 2 / 3, y: Int(pagerView.bounds.size.height) - 30, width: pageControlWidth, height: 30)
		
		pagerViewControl = FSPageControl(frame: pagerControlFrame)
		pagerViewControl.numberOfPages = self.imageNames.count
		pagerViewControl.contentHorizontalAlignment = .right
		pagerViewControl.contentInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
		
		pagerView.addSubview(pagerViewControl)
		
		self.mainTableView.tableHeaderView = pagerView
		
        
        // 加入主TableView
        view.addSubview(mainTableView)
    }
    
    deinit {
        self.mainTableView.dg_removePullToRefresh()
    }
    
    // 刷新主TableView
    internal func refreshMainTableView() -> () {
        
        // 清除主TableView的数据源
        self.topics.removeAllObjects()
        
        // 清除imageCache
        self.cache.removeAllObjects()
        
        // 主TableView除去下拉逻辑
        self.mainTableView.dg_removePullToRefresh()
        
        // 除去主TableView视图
        self.mainTableView.removeFromSuperview()
        
        // 重新获取并渲染UI
        self.getTopics(isMore: false)
    }
    
    
    /* ***********主TableView显示*********** */
    
    // 返回条数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return topics.count
    }
    
    // 返回Section个数
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    // 返回cell的高度 （因为使用了动态高度，所以这里不能再用了）
    /*
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    } 
    */
    
    
    // 返回主TableView的每一行
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // cell重用
        if let cell = tableView.dequeueReusableCell(withIdentifier: "TopicTableViewCell", for: indexPath) as? TopicTableViewCell {
            
            // 当前行数
            let row: Int = indexPath.row
            
            // 点击cell样式
            cell.selectionStyle = .none
            
            // 获取每一行的Title
            cell.titleLabel.text = (topics[row] as! Topic).title
            
            // 获取每一行的图片，图片来自于百度图片的智能搜索（基于Key Word），解析Baidu图片返回Json
            // 筛选关键字查询
            let parameters: Parameters = ["word": cell.titleLabel.text!]
            
            // 先检查是否在image cache中有图片，如果没有再去下载，cache中的key即为tablecell的index
            if (self.cache.object(forKey: (indexPath as NSIndexPath).row as AnyObject) != nil){
                cell.topicImage?.image = self.cache.object(forKey: (indexPath as NSIndexPath).row as AnyObject) as? UIImage
            } else {
                
                // 由于cell的重用问题，导致图片变来变去，可以先把image的source去掉
                cell.topicImage.image = nil
                
                // 请求百度图片取到image的URL
                Alamofire.request(Constants.baiduImageUrl, parameters: parameters).responseJSON { response in
                    if let JSONEntity = response.result.value {
                        let jsonData = JSON(JSONEntity)
                        if (jsonData["data"].count > 0) {
                            // 取中等大小图片地址
                            let imageURL: URL! = URL(string:jsonData["data"][0]["middleURL"].string!)
                            
                            // 在照片数组中添加照片地址
                            self.topicImages[row] = imageURL.absoluteString
                            
                            // 开始新的线程去下载图片放进image cache
                            self.task = self.session.downloadTask(with: imageURL, completionHandler: { (location, response, error) -> Void in
                                if let data = try? Data(contentsOf: imageURL){
                                    DispatchQueue.main.async(execute: { () -> Void in
                                        if let updateCell = tableView.cellForRow(at: indexPath) {
                                            let img:UIImage! = UIImage(data: data)
                                            cell.topicImage.image = img
                                            self.cache.setObject(img, forKey: (indexPath as NSIndexPath).row as AnyObject)
                                        }
                                    })
                                } else {
                                    // 如果没有图片，则用默认图
                                    cell.topicImage.image = #imageLiteral(resourceName: "default")
                                }
                            })
                            self.task.resume()
                            
                        } else {
                            // 如果没有图片，则用默认图
                            cell.topicImage.image = #imageLiteral(resourceName: "default")
                        }
                    }
                }
            }
            
            
            // 获取Topic的简短介绍
            cell.descLabel.text = (topics[row] as! Topic).summary
            
            // 取时间
            var timeMoment = moment() - moment((topics[row] as! Topic).createdAt!)!
            
            // 换成本地+8时区
            timeMoment = timeMoment - 8.hours
            
            // 设置时间
            if (timeMoment.seconds < 60) {
                cell.timeLabel.text = "现在"
            } else if (timeMoment.minutes < 60) {
                cell.timeLabel.text = String(Int(timeMoment.minutes)) + " 分钟前"
            } else if (timeMoment.hours < 24) {
                cell.timeLabel.text = String(Int(timeMoment.hours)) + " 小时前"
            } else {
                cell.timeLabel.text = String(Int(timeMoment.days)) + " 天前"
            }
            
            // 获取相关新闻个数
            let newArrayCount: Int = ((topics[row] as! Topic).newsArray?.count)!
            cell.triLabelView.labelText = String(newArrayCount)
                    
            
            //当下拉到底部，执行loadMore()
            if (loadMoreEnable && indexPath.row == self.topics.count - 1) {
                self.getTopics(isMore: true)
                let blankCell: UITableViewCell = UITableViewCell()
                
                return blankCell
            }
            
            // 设置顶部功能按钮
            // 1. 赞
            cell.likeBtn.isUserInteractionEnabled = true
			cell.likeBtn.tag = row
            let likeBtnTapped: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(TopicViewController.TappedLikeBtn(sender:)))
            likeBtnTapped.numberOfTapsRequired = 1
            cell.likeBtn.addGestureRecognizer(likeBtnTapped)
            
            
            // 判断是否点赞过, 防止cell重用图标乱掉
            if (zanArray.contains(row)) {
                cell.likeBtn.image = UIImage(named: "like2")
            } else {
                cell.likeBtn.image = UIImage(named: "like")
            }
	
            // 2. 赞的数量
            let likeNumberTapped: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(TopicViewController.TappedLikeNumber(sender:)))
            cell.likeNumber.tag = row
            cell.likeNumber.isUserInteractionEnabled = true
            cell.likeNumber.addGestureRecognizer(likeNumberTapped)

            // 生成随机点赞数
            cell.likeNumber.text = String(randomCustom(min: 0, max: 1000))
            
            // 3. 举报
            cell.jubaoBtn.isUserInteractionEnabled = true
			cell.jubaoBtn.tag = row
            let jubaoBtnTapped: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(TopicViewController.TappedjubaoBtn(sender:)))
            likeBtnTapped.numberOfTapsRequired = 1
            cell.jubaoBtn.addGestureRecognizer(jubaoBtnTapped)
            
            cell.jubaoBtn.image = UIImage(named: "jubao")
			
			// 判断是否举报过, 防止cell重用图标乱掉
			if (jubaoArray.contains(row)) {
				cell.jubaoBtn.image = UIImage(named: "jubao2")
			} else {
				cell.jubaoBtn.image = UIImage(named: "jubao")
			}
            
            // 4. 下载配图
            cell.downIMGBtn.isUserInteractionEnabled = true
            cell.downIMGBtn.tag = row
            let downIMGBtnTapped: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(TopicViewController.TappedDownBtn(sender:)))
            downIMGBtnTapped.numberOfTapsRequired = 1
            cell.downIMGBtn.addGestureRecognizer(downIMGBtnTapped)
            
            // 5. 分享
            cell.shareBtn.isUserInteractionEnabled = true
			cell.shareBtn.tag = row
            let shareBtnTapped: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(TopicViewController.TappedShareBtn(sender:)))
            shareBtnTapped.numberOfTapsRequired = 1
            cell.shareBtn.addGestureRecognizer(shareBtnTapped)
            
            // 6. 评论
            cell.commentBtn.isUserInteractionEnabled = true
			cell.commentBtn.tag = row
            let commentBtnTapped: UITapGestureRecognizer = UITapGestureRecognizer.init(target: self, action: #selector(TopicViewController.TappedCommentBtn(sender:)))
            commentBtnTapped.numberOfTapsRequired = 1
            cell.commentBtn.addGestureRecognizer(commentBtnTapped)
            
            // 返回cell
            return cell
        }
        
        // 返回默认cell
        return UITableViewCell()
    }
    
    // 点击"喜欢"按钮
	@objc func TappedLikeBtn(sender: UITapGestureRecognizer) {

        (sender.view as! UIImageView).image = UIImage(named: "like2")
        zanArray.append((sender.view?.tag)!)
        
    }
    
    // 点击"喜欢数字"Label
	@objc func TappedLikeNumber(sender: UITapGestureRecognizer) {
        
        let number = Int.init(string: (sender.view as! UILabel).text!)

        (sender.view as! UILabel).text! = String(number! + 1)
		
    }
	
    // 点击"举报"按钮
	@objc func TappedjubaoBtn(sender: UITapGestureRecognizer) {
        (sender.view as! UIImageView).image = UIImage(named: "jubao2")
		
		let jubaoID = (sender.view?.tag)!
		
		self.showJuBaoPage(id: jubaoID)

    }
    
    // 展示举报
	func showJuBaoPage(id: Int) -> () {
		
		let customWidth = self.view.bounds.width * 0.8
		
		let appearance = SCLAlertView.SCLAppearance(kWindowWidth: customWidth, showCloseButton: false, hideWhenBackgroundViewIsTapped: true)
		let alert = SCLAlertView(appearance: appearance)
		
		_ = alert.addButton("涉黄信息") {
			HUD.flash(HUDContentType.success, delay: 1.0)
			self.jubaoArray.append(id)
		}
		_ = alert.addButton("不实信息") {
			HUD.flash(HUDContentType.success, delay: 1.0)
			self.jubaoArray.append(id)
		}
		_ = alert.addButton("重复推送") {
			HUD.flash(HUDContentType.success, delay: 1.0)
			self.jubaoArray.append(id)
		}
		_ = alert.addButton("广告") {
			HUD.flash(HUDContentType.success, delay: 1.0)
			self.jubaoArray.append(id)
		}
		_ = alert.addButton("侵权") {
			HUD.flash(HUDContentType.success, delay: 1.0)
			self.jubaoArray.append(id)
		}
		_ = alert.addButton("取消", backgroundColor: Constants.redColor) {
			//print("")
		}
		
		_ = alert.showWarning("举报类型", subTitle:"")
		
    }
    
    // 点击"分享"按钮
	@objc func TappedShareBtn(sender: UITapGestureRecognizer) {
        
        // 取到Tag, 即cell的row
        let topicNumber = sender.view?.tag
        
        // 设置分享UI面板的顺序, 特殊写法
        UMSocialUIManager.setPreDefinePlatforms([NSNumber(integerLiteral:UMSocialPlatformType.wechatSession.rawValue),NSNumber(integerLiteral:UMSocialPlatformType.wechatTimeLine.rawValue),NSNumber(integerLiteral:UMSocialPlatformType.wechatFavorite.rawValue)])
        
        // 分享样式
        UMSocialUIManager.showShareMenuViewInWindow(platformSelectionBlock: { [unowned self] (type:UMSocialPlatformType, userInfo:[AnyHashable : Any]?) in
            
            let messageShare: UMSocialMessageObject = UMSocialMessageObject()
            
            // 设置分享样式
            
            let shareTitle = ((self.topics[topicNumber!]) as! Topic).newsArray?[0].title
            let shareObject: UMShareWebpageObject = UMShareWebpageObject.shareObject(withTitle: "精彩文章来自于 - iReadHub", descr: shareTitle, thumImage: #imageLiteral(resourceName: "logoforwechat"))
            
            // 设置分享URL (取topic的第一个news的mobile url)
            shareObject.webpageUrl = ((self.topics[topicNumber!]) as! Topic).newsArray?[0].mobileUrl
            
            messageShare.shareObject = shareObject;
            
            UMSocialManager.default().share(to: type, messageObject: messageShare, currentViewController: self, completion: nil)
        })
    }
    
    // 点击"下载"按钮
	@objc func TappedDownBtn(sender: UITapGestureRecognizer) {
        
        // 取到Tag, 即cell的row
        let topicNumber = sender.view?.tag
        
        // 初始化SKPhoto
        var images = [SKPhoto]()
		
		if (topicImages[topicNumber!] == nil || topicImages[topicNumber!] == "") {
			HUD.flash(HUDContentType.label("暂无图片查看"), delay: 2)
		} else {
        	let photo = SKPhoto.photoWithImageURL(topicImages[topicNumber!]!)
        	photo.shouldCachePhotoURLImage = false
        	images.append(photo)
        
        	// 初始化SKPhoto Browser
        	let browser = SKPhotoBrowser(photos: images)
        	browser.initializePageIndex(0)
        
        	// 弹出
        	present(browser, animated: true, completion: {})
		}
    }
    
    // 点击"评论"按钮
	@objc func TappedCommentBtn(sender: UITapGestureRecognizer) {
        
        //HUD.flash(HUDContentType.label("评论功能马上开放, 感谢关注"), delay: 2)
		
		// 取到Tag, 即cell的row
		let topicNumber = sender.view?.tag
		
		// 根据row取得Topic
		let topicTemp = topics[topicNumber!] as! Topic
		
		//拿到storyBoard
		let storyBoard = UIStoryboard(name: "Main", bundle: nil)
		//拿到ViewController
		let destination = storyBoard.instantiateViewController(withIdentifier: "TopicCommentViewController") as! TopicCommentViewController
		
		destination.transitioningDelegate = self
		destination.interactor = interactor
		
		//传值
		destination.topic = topicTemp
		
		// 展示
		self.present(destination, animated: true, completion: nil)
		
    }
    
    // 生成随机数
    func randomCustom(min: Int, max: Int) -> Int {
        let y = arc4random() % UInt32(max) + UInt32(min)
        return Int(y)
    }
    
    // 点击每个Cell的跳转
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        // 取得cell的row
        let row: Int = indexPath.row
        
        // 根据row取得Topic
        let topicTemp = topics[row] as! Topic
        
        //拿到storyBoard
        let storyBoard = UIStoryboard(name: "Main", bundle: nil)
        //拿到ViewController
        let destination = storyBoard.instantiateViewController(withIdentifier: "TopicNewsViewController") as! TopicNewsViewController
		
		destination.transitioningDelegate = self
		destination.interactor = interactor
		
        //传值
        destination.topic = topicTemp
        
        // 展示
        self.present(destination, animated: true, completion: nil)
    }
    
    //上拉刷新视图
    private func setupInfiniteScrollingView() {
        
        // 定义刷新视图的Frame
        let loadMoreViewFrame = CGRect(x: 0, y: self.mainTableView.contentSize.height, width: self.mainTableView.bounds.size.width, height: 30)
        
        // 设置刷新视图
        self.loadMoreView = UIView(frame: loadMoreViewFrame)
        self.loadMoreView!.autoresizingMask = UIViewAutoresizing.flexibleWidth
        self.loadMoreView!.backgroundColor = UIColor.white
        
        //添加中间的环形进度条
        let activityViewIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
        activityViewIndicator.color = Constants.mainTextColor
        let indicatorX = self.loadMoreView!.frame.size.width/2-activityViewIndicator.frame.width/2
        let indicatorY = self.loadMoreView!.frame.size.height/2-activityViewIndicator.frame.height/2
        
        activityViewIndicator.frame = CGRect(x: indicatorX, y: indicatorY,
                                             width: activityViewIndicator.frame.width,
                                             height: activityViewIndicator.frame.height)
        activityViewIndicator.startAnimating()
        self.loadMoreView!.addSubview(activityViewIndicator)
    }
    
    // 返回自己的view, 如果是传值过来的页面则必须要重写这个方法, 否则不显示分享UI面板
    func umSocialParentView(_ defaultSuperView: UIView!) -> UIView! {
        return self.view
    }
	
//	override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//		if let destinationViewController = segue.destination as? TopicNewsViewController {
//			destinationViewController.transitioningDelegate = self
//			destinationViewController.interactor = interactor
//		}
//	}
	
}

extension TopicViewController: UIViewControllerTransitioningDelegate {
	func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
		return DismissAnimator()
	}
	
	func interactionControllerForDismissal(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
		return interactor.hasStarted ? interactor : nil
	}
}

// Support TableView Header
extension TopicViewController: FSPagerViewDataSource, FSPagerViewDelegate {
	
	// 3
	public func numberOfItems(in pagerView: FSPagerView) -> Int {
		return 3
	}
	
	// 返回cell
	public func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
		let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)
		cell.imageView?.image = UIImage(named: self.imageNames[index])
		cell.imageView?.contentMode = .scaleAspectFill
		cell.imageView?.clipsToBounds = true
		//cell.textLabel?.text = index.description+index.description
		return cell
	}
	
	func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
		pagerView.deselectItem(at: index, animated: true)
		pagerView.scrollToItem(at: index, animated: true)
		self.pagerViewControl.currentPage = index
		
		let pageURL = self.ADHomePages[index]
		
		let webVC = SwiftModalWebVC(urlString: pageURL, theme: .dark, dismissButtonStyle: .arrow)
		
		self.present(webVC, animated: true, completion: nil)
		
	}
	
	func pagerViewDidScroll(_ pagerView: FSPagerView) {
		guard self.pagerViewControl.currentPage != pagerView.currentIndex else {
			return
		}
		self.pagerViewControl.currentPage = pagerView.currentIndex
	}
}


extension UIImage {
    class func imageWithColor(_ color: UIColor) -> UIImage {
        let rect: CGRect = CGRect(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContextWithOptions(CGSize(width: 1, height: 1), false, 0)
        color.setFill()
        UIRectFill(rect)
        let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return image
    }
}

class HighlightableButton: UIButton{
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setup()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setup()
    }
    
    func setup() {
        backgroundColor = #colorLiteral(red: 0.1019607843, green: 0.737254902, blue: 0.6117647059, alpha: 1)
        layer.cornerRadius = 5
        layer.masksToBounds = true
    }
    
    override var isHighlighted: Bool{
        set{
            UIView.animate(withDuration: 0.1) { [weak self] in
                self?.alpha = newValue ? 0.5 : 1
                self?.transform = newValue ? CGAffineTransform(scaleX: 0.95, y: 0.95) : .identity
            }
            super.isHighlighted = newValue
        }get{
            return super.isHighlighted
        }
    }
}
